package com.qf.service.impl;

import com.qf.dao.RoutationRepository;
import com.qf.pojo.entity.RotationImage;
import com.qf.pojo.repVo.BaseResp;
import com.qf.service.RoutationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class RoutationServiceImpl implements RoutationService {

    @Autowired
    RoutationRepository routationRepository;

    @Autowired
    RedisTemplate redisTemplate;

    private static final String ROUTATION_IMAGE="routation_image";

    @Override
    public BaseResp findRatation() {

        //1.判断Redis中是否有轮播图
        Boolean aBoolean = redisTemplate.hasKey(ROUTATION_IMAGE);
        Set set=null;
        if (aBoolean){
            //代表redis中已经存在该key值，直接获取数据，并且按照score获取
            //redis中的zset数据可以进行排序处理
             set = redisTemplate.opsForZSet().reverseRange(ROUTATION_IMAGE, 0, -1);
        }else {
            //如果redis中没有，我们需要先查询数据库，放置到redis中
            List<RotationImage> all = routationRepository.findAll();
            for (RotationImage ri:all
                 ) {
                redisTemplate.opsForZSet().add(ROUTATION_IMAGE,ri,Double.valueOf(ri.getImageIndex()));
            }

            set = redisTemplate.opsForZSet().reverseRange(ROUTATION_IMAGE, 0, -1);

        }

        return new BaseResp(1,"查询成功！",set,null);
    }
}
